package com.xsb.mvvmlibrary.network

import com.xsb.mvvmlibrary.network.interceptor.BaseUrlInterceptor
import com.xsb.mvvmlibrary.network.interceptor.RetrofitInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *     author : 薛少博
 *     e-mail : xsb@zlhopesun.com
 *     time   : 2021/5/19
 *     desc   : 初始化Retrofit
 */
class ApiRetrofit {
    //定义连接超时时间
    val DEFAULT_TIMEOUT = 60
    val retrofit: Retrofit

    companion object {
        private var instance: ApiRetrofit? = null

        /**
         * 方法描述：获取实例
         * @author 薛少博
         * ==========================
         * @param
         * @return
         */
        fun getInstance(): ApiRetrofit? {
            if (instance == null) {
                synchronized(ApiRetrofit::class.java) {
                    if (instance == null) {
                        instance = ApiRetrofit()
                    }
                }
            }
            return instance
        }
    }

    /**
     * 方法描述：初始化retrofit
     * @author 薛少博
     * ==========================
     * @param
     * @return
     */
    init {
        val okHttpClient = OkHttpClient.Builder().addInterceptor(RetrofitInterceptor())
            .addInterceptor(BaseUrlInterceptor())
            .connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .dns(ApiDns()).build()
        retrofit = Retrofit.Builder()
            .baseUrl("https://wanandro.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(okHttpClient)
            .build()
    }
}